package LeetCode;

public class StrtoInt
{
  //just need to handle integer_min cases
  public static int atoi(String str) {
    // Start typing your Java solution below
    // DO NOT write main() function
    
    if(str == null || str.isEmpty())
      return 0;
    str = str.trim();
    int result = 0;
    boolean negative = false;
    if(str.charAt(0) == '-')
      negative = true;
    
    int start = 0;
    if(negative)
      start = 1;
    if(str.charAt(0) == '+')
      start = 1;
    
    for(int i = start; i < str.length(); i++){
      int digit =  (str.charAt(i) - '0');
      if(digit >= 0 && digit < 10){
        if(result > (Integer.MAX_VALUE - digit) / 10){
          result = Integer.MAX_VALUE;
          break;
        }
        result  = result * 10 + digit;
      }
      else
        break;
    }
    if(result == Integer.MAX_VALUE && negative)
      result = Integer.MIN_VALUE;
    else if(negative)
      result *= -1;
    return result;
    
  }
  /**
   * @param args
   */
  public static void main(String[] args)
  {
    // TODO Auto-generated method stub
    System.out.println(atoi("-2147483648"));

  }

}
